import websocket
import threading
import json
# ws://10.128.241.126:8000/ws/
ws = None

serverUrl = "ws://192.168.137.1:8080/ws/?room_id=raspi&user_id=raspi"

ws_thread = None


def on_message(ws, message):
    print("收到消息")
    print(message)
    from .info import recvInfoDispose
    recvInfoDispose(json.loads(message))


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")
    from .info import clearParam
    clearParam()


def on_open(ws):
    print("### connection ###")


def create_connection():
    global ws, ws_thread
    websocket.enableTrace(False)
    ws = websocket.WebSocketApp(serverUrl,
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws_thread = threading.Thread(target=ws.run_forever, name='WebSocketThread')
    ws_thread.start()


def ws_send(data: dict):
    global ws
    str = json.dumps(data)
    print(str)
    ws.send(str)